package com.dexilaonian.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import com.dexilaonian.MainActivity;
import com.dexilaonian.R;
import com.dexilaonian.permission.AfterPermissionGranted;
import com.dexilaonian.permission.PermissionUtils;
import com.dexilaonian.utils.ADFilterTool;
import com.dexilaonian.utils.BitmapZip;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.utils.FileUtils;
import com.dexilaonian.utils.ImageLoader;
import com.dexilaonian.utils.Okhttp;
import com.dexilaonian.utils.PreferencesUtil;
import com.dexilaonian.view.LoadingDialog;
import com.dexilaonian.view.MultiImageSelectorActivity;

import org.codehaus.jackson.smile.Tool;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class ConsultationActivity extends AppCompatActivity {
    private static final int CAMERA_PERIMISSION_CODE = 20;
    private static final int REQUEST_IMAGE = 21;
    ////健康管理
    private WebView consul_web;
    private String url2;
    private LoadingDialog dialog;
    private ArrayList<String> mSelectPath = new ArrayList<>();
    private String imageUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_consultation);
        consul_web = (WebView) findViewById(R.id.consultation_web);
        clearWebViewCache();
        String url = Constant.base_url + "/health";
        dialog = new LoadingDialog(this);

        if (!TextUtils.isEmpty(PreferencesUtil.getString(ConsultationActivity.this, Constant.KEY))) {
            url2 = url + "?token=" + PreferencesUtil.getString(ConsultationActivity.this, Constant.KEY);
        }
        init();
        //  Log.e("TTTTTTTTTTTT", url2);
    }
    //与H5交互调用相机
    public void initCamera() {
        String[] perms = new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (PermissionUtils.hasPermissions(ConsultationActivity.this, perms)) {
            startPickPicActivity();
        } else {
            PermissionUtils.requestPermissions(ConsultationActivity.this, "需要拍照和相册权限", CAMERA_PERIMISSION_CODE, perms);
            initCamera();
        }
    }

    @AfterPermissionGranted(CAMERA_PERIMISSION_CODE)
    public void startPickPicActivity() {
        int selectedMode = MultiImageSelectorActivity.MODE_MULTI;
        //selectedMode = MultiImageSelectorActivity.MODE_SINGLE;
        boolean showCamera = true;
        int maxNum = 1;
        Intent intent = new Intent(this, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, showCamera);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, maxNum);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, selectedMode);
        // 默认选择
        if (mSelectPath != null && mSelectPath.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
        }
        startActivityForResult(intent, REQUEST_IMAGE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == RESULT_OK) {
                mSelectPath = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                for (int i = 0; i < mSelectPath.size(); i++) {
                    postFile(new File(mSelectPath.get(i)));
                }
            }
        }
    }

    private void postFile(File file) {
        final String pic_path = file.getPath();
        String targetPath = FileUtils.getSDCardPath() + file.getName();
        //压缩图片的方法
        final String compressImage = BitmapZip.compressImage(pic_path, targetPath, 90);
        final File compressedPic = new File(compressImage);
        if (compressedPic.exists()) {
            file = compressedPic;
        }
        Map<String, String> params = new HashMap<>();
        params.put("type", "1");
        dialog.show();
        String url = Constant.base_url + "/upload/image";
        Okhttp.postFileParams(url, file, params, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                Toast.makeText(ConsultationActivity.this, state, Toast.LENGTH_SHORT).show();
                dialog.cancel();
            }

            @Override
            public void onResponse(final String response, int id) {
                Log.e("TTT上传头像", response);
                dialog.cancel();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String content = jsonObject.optString("data");
                    JSONObject content_json = new JSONObject(content);
                    String face = content_json.optString("path");
                    if (!TextUtils.isEmpty(face)) {
                        imageUrl = Constant.base_pic_url + face;
                        new DownloadImageTask().execute(imageUrl);
                        PreferencesUtil.putString(ConsultationActivity.this, Constant.IMAGE, imageUrl);
                        Log.e("TTTTH5头像", imageUrl);
                        consul_web.post(new Runnable() {
                            @Override
                            public void run() {
                                consul_web.loadUrl("javascript:jsFormNavtive('" + imageUrl + "')");
                            }
                        });
                        //Toast.makeText(ConsultationActivity.this, "头像上传成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(ConsultationActivity.this, "头像上传失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNoNetwork(String state) {
                dialog.cancel();
            }
        });
    }

    private class DownloadImageTask extends AsyncTask<String, Void, Drawable> {

        protected Drawable doInBackground(String... urls) {
            return loadImageFromNetwork(urls[0]);
        }

        protected void onPostExecute(Drawable result) {
        }
    }

    private Drawable loadImageFromNetwork(String imageUrl) {
        Drawable drawable = null;
        try {
            // 可以在这里通过第二个参数(文件名)来判断，是否本地有此图片
            drawable = Drawable.createFromStream(new URL(imageUrl).openStream(), null);
        } catch (IOException e) {
            Log.e("TTTskythinking", e.getMessage());
        }
        return drawable;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (keyCode == keyEvent.KEYCODE_BACK) {
            if (consul_web.canGoBack()) {
                consul_web.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, keyEvent);
    }

    private void init() {
        WebSettings webSettings = consul_web.getSettings();
        // 让WebView能够执行javaScript
        webSettings.setJavaScriptEnabled(true);

        // 让JavaScript可以自动打开windows
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        // 设置缓存模式,一共有四种模式
        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        // 设置缓存路径
//        webSettings.setAppCachePath("");
        // 支持缩放(适配到当前屏幕)
        webSettings.setSupportZoom(true);
        // 将图片调整到合适的大小
        webSettings.setUseWideViewPort(true);
        // 支持内容重新布局,一共有四种方式
        // 默认的是NARROW_COLUMNS
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        // 设置可以被显示的屏幕控制
        webSettings.setDisplayZoomControls(true);
        // 设置默认字体大小
        webSettings.setDefaultFontSize(12);
        // 设置WebView的客户端
        consul_web.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
        consul_web.getSettings().setAppCachePath(appCachePath);
        consul_web.getSettings().setDomStorageEnabled(true);
        consul_web.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        consul_web.clearCache(true);
/*        consul_web.getSettings().setAllowFileAccess(true);
        consul_web.getSettings().setAppCacheEnabled(true);*/
        consul_web.setWebViewClient(new NoAdWebViewClient(ConsultationActivity.this,"http://dxccmc.com/health"));//拦截广告
        consul_web.addJavascriptInterface(new JavaScriptinterface(ConsultationActivity.this), "android");
        consul_web.setWebChromeClient(new WebChromeClient() {
            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
        });
        consul_web.loadUrl(url2);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        consul_web.getSettings().setDomStorageEnabled(false);
        consul_web.getSettings().setAllowFileAccess(false);
        consul_web.getSettings().setAppCacheEnabled(false);
        consul_web.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        consul_web.clearCache(true);
    }

    // 拦截广告
    public class NoAdWebViewClient extends WebViewClient {
        private String homeurl;
        private Context context;

        public NoAdWebViewClient(Context context,String homeurl) {
            this.context = context;
            this.homeurl = homeurl;
        }
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            url = url.toLowerCase();
            if(!url.contains(homeurl)){
                if (!ADFilterTool.hasAd(context, url)) {
                    return super.shouldInterceptRequest(view, url);
                }else{
                    return new WebResourceResponse(null,null,null);
                }
            }else{
                return super.shouldInterceptRequest(view, url);
            }
        }
    }
    public void clearWebViewCache(){
        File file = this.getApplicationContext().getCacheDir().getAbsoluteFile();
        deleteFile(file);
    }
    /**
     * 递归删除 文件/文件夹
     *
     * @param file
     */
    public void deleteFile(File file) {

        Log.i("TAG", "delete file path=" + file.getAbsolutePath());

        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
            Log.e("TAG", "delete file no exists " + file.getAbsolutePath());
        }
    }
}
